;*******************************************************************************
; Title:	IfModule
; Author:	Philip Ludlam
; Copyright:	(C) Philip J. Ludlam 2014
; Version:	1.00 (25 Jan 2014)
;
; Changes:	Initial version
;
;*******************************************************************************
; This program is free software; you can redistribute it and/or modify it
; under the terms of the GNU General Public License as published by the Free
; Software Foundation; either version 2 of the License, or (at your option)
; any later version.
;
; This program is distributed in the hope that it will be useful, but WITHOUT
; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
; FITNESS FOR APARTICULAR PURPOSE. See the GNU General Public License for more
; details.
;
; You should have received a copy of the GNU General Public License along with
; this program; if not, write to the Free Software Foundation, Inc., 59 Temple
; Place - Suite 330, Boston, MA 02111-1307, USA
;
;*******************************************************************************


		TTL	> IfModule

		GET	OSLib:oslib.hdr.OS
		GET	OSLib:oslib.hdr.OSModule
		GET	AsmLib2:hdr.RegsBoth

arg_module	*	&0
arg_command	*	&4
arg_yes		*	&8
arg_no		*	&C

		AREA	|main|, CODE, READONLY

		ENTRY

;-------------------------------------------------------------------------------

Start		B	Entry			; Entry instruction
		DCD	&79766748		; Magic value 1
		DCD	&216C6776		; Magic value 2
		DCD	End-Start		; Read only size
		DCD	0			; Read/write size
		DCD	32			; 26 or 32 bit build

Entry

		MOV	r11, lr				; Store lr in r11

		ADR	r0, args
		MOV	r2, wp
		MOV	r3, #1024
		SWI	XOS_ReadArgs
		BVS	syntax_code_err			; Error parsing the arguments

		LDR	r0, [wp, #arg_command]
		CMP	r0, #0
		BEQ	syntax_code			; It passes the basic syntax check

		SUB	r8, r13, r3			; r8 = next free block in workspace

do
                MOV     r0, #OSModule_Lookup		; r0 = 18
		LDR	r1, [wp, #arg_module]
                SWI     XOS_Module
		BVS	do_command_no		; If it errors, we can only assume that the module does not exist


do_command_yes
		LDMIA	wp, {r0, r5, r6, r7}
		TEQ	r7, #0
		MOVEQ	r6, #0
		B	do_command

do_command_no
		LDMIA	wp, {r0, r5, r6, r7}
		TEQ	r6, #0
		TEQNE	r7, #0
		MOVNE	r6, r7
		BNE	do_command
		TEQ	r6, #0
		BEQ	exit
		MOV	r5, r6
		MOV	r6, #0

do_command
		MOV	r1, r8
		MOV	r0, r5
		MOV	r2, #32
		BL	copy
		MOVS	r0, r6
		MOV	r2, #0
		BLNE	copy
		STREQB	r2, [r1, #-1]

os_cli
		MOV	r0, r8
		SWI	XOS_CLI

exit
		MOV	pc, r11


copy
		LDRB	r3, [r0], #1
		STRB	r3, [r1], #1
		CMP	r3, #32
		BGE	copy
		STRB	r2, [r1, #-1]
		MOV	pc, lr


error
		SetV
errored
		MOV	pc, r11


syntax_code
		SetV
syntax_code_err
		ADR	r0, syntax
		MOV	pc, r11


syntax
		DCD	0
		DCB	"Syntax: *IfModule <module name> <yes command> [<no command>]", 10, 13
		DCB	"or:     *IfModule <module name> <command> <yes param> <no param>"
		DCB	0
		ALIGN

args
		DCB	",,,"
		DCB	0

licence		DCB	" PJL, 2014. Licence: GPL."
		ALIGN

End

		END
